package com.zf.nospring.kafka.manual;

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Properties;

/**
 * 消费者手动提交
 */
public class ConsumerManualCommit {
    public static void main(String[] args) {
        // 创建消费者的配置对象
        Properties properties = new Properties();
        // kafka broker的地址
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        // 配置序列化 必须
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        // 配置消费者组ID，任意起名，必传
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "defaultCG");

        // 一次 poll 拉取，获取消息的最大条数，默认是 500 条。
        properties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 20);

        // 关闭自动提交offset功能
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

        // 创建消费者对象
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);

        // 订阅主题
        kafkaConsumer.subscribe(Arrays.asList("test"));


        while (true) {
            ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.ofSeconds(2));
            for (ConsumerRecord<String, String> record : consumerRecords) {
                System.out.println(record);
            }
            // 如果获取到了消息就手动提交offset
            if (!consumerRecords.isEmpty()) {
                // 直接提交，为订阅的主题和分区列表提交上次poll()返回的偏移量。
                // kafkaConsumer.commitSync();

                // 或者提交指定的主题和分区的偏移量，提交的偏移量应该是将要获取的下一条消息，所以 offset要+1
                HashMap<TopicPartition, OffsetAndMetadata> offsetMap = new HashMap<>();
                for (ConsumerRecord<String, String> record : consumerRecords) {
                    offsetMap.put(new TopicPartition(record.topic(), record.partition()), new OffsetAndMetadata(record.offset() + 1));
                }
                kafkaConsumer.commitSync(offsetMap);
            }
        }
    }
}
